<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
      <view style="text-align: center; margin-bottom: 50rpx;">首页</view>
      <Record />
      <!-- 添加天气展示区域 -->
      <view class="hefeng-weather" v-if="weatherData">
        <view class="weather-container">
          <view class="weather-info">
            <view class="location-name">{{ address }}</view>
            <view class="temperature">{{ weatherData.now.temp }}°C <span class="weather-desc">{{ weatherData.now.text }}</span></view>
          </view>
          <view class="weather-icon">
            <i class="qi-100" style="font-size: 60rpx;"></i>
          </view>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <swiper class="banner" :autoplay="true" :interval="3000" indicator-dots indicator-color="rgba(255,255,255,0.5)"
      indicator-active-color="#fff" circular>
      <swiper-item v-for="(item, index) in banners" :key="index">
        <image :src="item.image" class="banner-image" mode="aspectFill"></image>
      </swiper-item>
    </swiper>
    <!-- 功能入口 -->
    <view class="function-grid">
      <view v-for="(item, index) in functions" :key="index" class="function-item" @click="navigateTo(item.page)">
        <image :src="item.icon" class="function-icon"></image>
        <text>{{ item.name }}</text>
      </view>
    </view>

    <!-- 健康测评 -->
    <view class="health-test">
      <view class="section-title">
        <text>健康测评</text>
        <text class="more" @click="navigateTo('')">更多 ></text>
      </view>
      <view class="test-card">
        <view class="test-title">今日健康自测</view>
        <view class="test-desc">10道题评估您的健康状况</view>
        <button class="start-btn" @click="navigateTo('/pages/index/components/healthTest')">开始测评</button>
      </view>
    </view>
    <!-- 疫苗预约 -->
    <view class="vaccine-section">
      <view class="section-title">
        <text>疫苗预约</text>
        <text class="more" @click="navigateTo('')">更多 ></text>
      </view>
      <view class="vaccine-card">
        <image src="" class="vaccine-bg"></image>
        <view class="vaccine-content">
          <text class="vaccine-title">新冠疫苗加强针预约</text>
          <text class="vaccine-desc">18岁以上人群可接种第三针</text>
          <button class="appoint-btn" @click="navigateTo('/pages/index/components/vaccine')">立即预约</button>
        </view>
      </view>
    </view>

    <!-- 健康数据统计 -->
    <echarts />
  </view>
</template>

<script>
import Vue from 'vue';
import { getCurrentAddress } from '../../utils/qqMap'
import echarts from '../../components/echarts.vue';
import Record from '../../components/record.vue';
import api from '@/api/index'
import { pinyin } from 'pinyin-pro'; //文字转拼音
export default Vue.extend({
  components: { echarts, Record },
  data() {
    return {
      safeAreaInsets: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      address: '', //地址
      banners: [],
      functions: [],
      apiKey: '2cebca35969744d3b06f77850b196885',
      cityId: '',
      weatherData: null,
      error: null,
    }
  },

  computed: {
  },
  methods: {
    // 添加获取天气图标的方法
    getWeatherIconUrl(iconCode) {
      // 确保图标代码是有效的
      if (!iconCode || typeof iconCode !== 'string') {
        iconCode = '100'; // 默认使用晴天图标
      }
      // 返回SVG图标路径
      return `/static/weather-icons/${iconCode}.svg`;
    },
    // 添加 navigateTo 方法
    navigateTo(url) {
      // 获得token
      const token = uni.getStorageSync('token');
      console.log('token', token);
      //等登陆页面完成，这里放token验证
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      uni.navigateTo({
        url: url
      });

    },

    //获取轮播图的数据
    async getimagesapi() {
      try {
        // 正确的调用方式
        const res = await api.getImageApi()
        // 或者如果你用了命名导入：const res = await getUserApi()
        console.log('res', res);
        this.banners = res.data
      } catch (error) {
        console.error('获取图片数据失败:', error);
      }
    },
    //获取菜单导航栏的数据
    async getfunctionsapi() {
      try {
        // 正确的调用方式
        const res = await api.getFunctionsApi()
        // 或者如果你用了命名导入：const res = await getUserApi()
        console.log('res', res);
        this.functions = res.data
      } catch (error) {
        console.error('获取菜单列表失败:', error);
      }
    },
    //定位
    async fetchAddress() {
      try {
        uni.showLoading({ title: '定位中' })
        const res = await getCurrentAddress()
        this.address = res.formatted_addresses.recommend
        const addressPinyin = res.ad_info.city
        // console.log('111111', this.address);
        this.pinyinConvert(addressPinyin)
      } catch (err) {
        this.address = '获取位置失败'
        console.error(err)
      } finally {
        uni.hideLoading()
      }
    },
    //转拼音
    pinyinConvert(text) {
      // console.log('text', text);
      // console.log('pinyin', pinyin(text, { toneType: 'none' }));
      const res = pinyin(text, { toneType: 'none' });
      this.convertLatLonToLocationId(res);
    },
    //通过拼音地址获得locationId（经测试，不需要字符串转拼音，直接用字符串也可以获取locationId）
    async convertLatLonToLocationId(text) {
      // console.log('111121323', text);
      try {
        const response = await uni.request({
          url: `https://jx564u3an5.re.qweatherapi.com/geo/v2/city/lookup?location=${text}&key=${this.apiKey}`,
          method: 'GET',
        });
        //给一个判断，api调用成功走下面的逻辑
        if (response.data.code === '200' && response.data.location.length > 0) {
          this.locationId = response.data.location[0].id;
          this.cityId = this.locationId; // 更新城市ID
          // console.log('转换成功，locationId：', this.locationId);
          this.fetchWeatherData();
        } else {
          this.error = `转换失败：${response.data.code} - ${response.data.msg}`;
          console.error(this.error);
        }
      } catch (err) {
        this.error = `请求错误：${err.message}`;
        console.error(this.error);
      }
    },
    //通过locationId获得天气数据
    async fetchWeatherData() {
      console.log(11111);

      try {
        // 调用和风天气API
        const response = await uni.request({
          url: `https://jx564u3an5.re.qweatherapi.com/v7/weather/now?location=${this.cityId}&key=${this.apiKey}`,
          method: 'GET',
        });
        // 检查响应状态
        if (response.data.code === '200') {
          this.weatherData = response.data;
          console.log(`当前${this.address}天气数据获取成功:`, this.weatherData);
        } else {
          this.error = `获取失败: ${response.data.code} - ${response.data.msg}`;
          console.error(this.error);
        }
      } catch (err) {
        this.error = `请求错误: ${err.message}`;
        console.error(this.error);
      }
    },
    onLoad() {
      try {
        // 获取系统信息（包含安全区域）
        const systemInfo = uni.getSystemInfoSync();
        // 赋值安全区域信息（兼容部分设备无此属性的情况）
        this.safeAreaInsets = systemInfo.safeAreaInsets || this.safeAreaInsets;
      } catch (e) {
        console.error('获取系统信息失败:', e);
      }
      this.fetchAddress()
      this.getimagesapi()
      this.getfunctionsapi()
    }
  }
})

</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
    Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: #333;
}

.container {
  padding-bottom: 70px;
}

/* 头部样式 */
.header {
  width: 100%;
  background-image: url('https://pic.mksucai.com/00/46/41/5689842c13df52e4.webp');
}

.search-box input {
  width: 85%;
  height: 32px;
  background: #f0f2f5;
  border-radius: 16px;
  padding-left: 80rpx;
  font-size: 14px;
  margin-left: 20rpx;
}

.search-box {
  position: relative;
}

.search-icon {
  position: absolute;
  left: 20rpx;
  top: 8px;
  width: 16px;
  height: 16px;
}


/* 轮播图 */
.banner {
  height: 400rpx;
  border-radius: 10rpx;
  overflow: hidden;
  margin-bottom: 20px;
}

.banner-image {
  width: 100%;
  height: 100%;
}

/* 功能网格 */
.function-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
}

.function-item text {
  font-size: 12px;
  color: #555;
}

/* 健康测评 */
.health-test {
  background: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.more {
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.test-card {
  background: linear-gradient(to right, #4a90e2, #5fa7f5);
  border-radius: 8px;
  padding: 15px;
  color: white;
  position: relative;
  overflow: hidden;
}

.test-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.test-desc {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 15px;
}

.start-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.5);
  color: white;
  width: 100px;
  height: 32px;
  line-height: 32px;
  border-radius: 16px;
  font-size: 14px;
  padding: 0;
}

/* 科室网格 */
.appointment-section {
  background: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.dept-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.dept-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.dept-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
}

/* 疫苗预约 */
.vaccine-section {
  background: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.vaccine-card {
  background: linear-gradient(to right, #34b7aa, #4cd1c0);
  border-radius: 8px;
  height: 120px;
  position: relative;
  overflow: hidden;
}

.vaccine-bg {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 120px;
  opacity: 0.2;
}

.vaccine-content {
  position: relative;
  padding: 15px;
  color: white;
  z-index: 2;
}

.vaccine-title {
  font-size: 16px;
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.vaccine-desc {
  font-size: 12px;
  opacity: 0.9;
  display: block;
  margin-bottom: 15px;
}

.appoint-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.5);
  color: white;
  width: 100px;
  height: 32px;
  line-height: 32px;
  border-radius: 16px;
  font-size: 14px;
  padding: 0;
}

/* 图表区域 */
.echarts-section {
  background: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.echarts-container {
  width: 100%;
  height: 250px;
}

/* 底部导航 */
.tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  display: flex;
  border-top: 1px solid #eee;
  z-index: 100;
}

.tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.tabbar-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 3px;
}

.tabbar-item text {
  font-size: 10px;
  color: #999;
}

.active {
  color: #4a90e2 !important;
}

/* 和风天气样式 */
.hefeng-weather {
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.weather-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.weather-info {
  width: 96%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.location-name {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.temperature {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.weather-desc {
  font-size: 14px;
  color: #666;
}

.weather-icon {
  font-size: 80rpx;
  color: #ff9900;
}
</style>